package com.property.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.property.mapper.ResidentMapper;
import com.property.pojo.Resident;
import com.property.service.ResidentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

@Service
public class ResidentServiceImpl implements ResidentService {
    @Autowired
    private ResidentMapper residentMapper;
    @Override
    public String findAllResident(Integer page) {
        PageHelper.startPage(page,10);
        List<Resident> list =residentMapper.findAllResident();
        PageInfo pageInfo = new PageInfo(list);
        return JSON.toJSONString(pageInfo);
    }
    //新增
    @Override
    public String saveResident(Resident resident) {
        String message = "操作成功";
        int num=0;
        //定义判别用户身份证号的正则表达式（要么是15位，要么是18位，最后一位可以为字母）
        String regularExpression =
                "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|"
                        + "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
        String REGEX_MOBILE = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        if(!checkResident(resident)){    //判断数据是否为空 输入属性有空
            message = "数据不能为空";
        }else if(!Pattern.matches(regularExpression,resident.getrIdnumber())){ //判断身份证格式
            message="身份证格式不对";
        }else if(!Pattern.matches(REGEX_MOBILE,resident.getrPhone())){ //判断手机号格式
            message = "手机号格式不正确";
        }else{
            if(resident.getrId() != null){  //判断是否有id 如果id不为空 为更新
                num= residentMapper.updateResident(resident);
            }else {
                num = residentMapper.saveResident(resident);
            }
            if(num <=0){
                message="操作失败";
            }
        }
        return JSON.toJSONString(message);
    }

    @Override
    public int deleteResident(Integer rId) {
        return residentMapper.deleteResident(rId);
    }

    @Override
    public Resident findResidentByrId(Integer rId) {
        return residentMapper.findResidentByrId(rId);
    }

    //判断住户信息是否有空
    private static boolean checkResident(Resident resident){
        boolean flag = true;
        if(resident.getrName() ==null || resident.getrName().equals("") || resident.getrSex() ==null || resident.getrSex().equals("")
                || resident.getrPhone()==null ||resident.getrPhone().equals("") || resident.getrIdnumber()==null ||resident.getrIdnumber().equals("")||
        resident.getrBid() == null || resident.getrBid()==0){
            flag = false;
        }
        return flag;
    }
}
